<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2009 Christian Kartnig <office@hahnepeter.de>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */


require_once(t3lib_extMgm::extPath('topstip').'lib/class.topstip_pibase.php');
require_once(PATH_t3lib.'class.t3lib_htmlmail.php');
// include all tca files in folder kb_config/dyn
$tcaFiles = glob(t3lib_extMgm::extPath('kb_config') . 'dyn/tca_*.php');
foreach($tcaFiles as $k=>$v) {
	require_once($v);
} 
 

/**
 * Plugin 'formidable_test' for the 'test' extension.
 *
 * @author	Christian <office@hahnepeter.de>
 * @package	TYPO3
 * @subpackage	tx_test
 */
class tx_topstip_pi1 extends topstip_pibase {
	var $prefixId      = 'tx_topstip_pi1';		// Same as class name
	var $scriptRelPath = 'pi1/class.tx_topstip_pi1.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'topstip';	// The extension key.
	var $pi_checkCHash = true;
	
	var $uid;
	var $record;
	var $configArray;
	var $test;

	
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content, $conf) {
		//$this->conf = $conf;
		$this->conf = $this->getGeneralTS();
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();

		$this->pi_initPIflexForm();

		$this->uid = intval($this->piVars['uid']);
		$tableKey = $this->piVars['tableKey'];

		$this->configArray = $this->getConfigArray($tableKey);

		$this->oForm = t3lib_div::makeInstance("tx_ameosformidable");
		
		if(sizeof($this->configArray) > 0) {

			if ($this->uid > 0) {

				$this->record = $this->getRecord(); 

				if (!$this->isAdmin() && $this->record['tx_kbks_fe_user'] != $GLOBALS['TSFE']->fe_user->user['uid']) {
					return 'Sie haben nicht die Berechtigung, diesen Antrag anzuzeigen.';
				}

				$this->oForm->init(
					$this,	// reference to the current plugin object
					$this->configArray['tx_kbks_xmlpath'], // soft-path to xml file
					$this->uid
				);
			} else {
				$this->oForm->init(
					$this,	// reference to the current plugin object
					$this->configArray['tx_kbks_xmlpath'] // soft-path to xml file
				);
			}

			return $this->oForm->render();
		
		} else {
			return 'wrong parameters!';
		}

	}

	/**
	 * Processes status, renders and sends emails if necessary
	 *
	 * @param aData		contains data of the submitted form
	 *	 	 
	 * @return	boolean
	 */
	function processStatus($aData) {
		
		if (!($this->uid > 0)) {
			/* no uid -> new record, status=1 */
			$status = 1;
			$statusOld = 0;
		} else {
			/* get old status from db */
			$status = $aData['tx_kbks_status'];
			$statusOld = $this->record['tx_kbks_status'];
		}
		
		if ($status > $statusOld) {
					
			$template = $this->cObj->fileResource($this->conf['emailTemplate']);
			
			switch ($status) {
		    case 1:
		        /* offen: send Email */
						$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_OFFEN_PLAIN###');
						$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_OFFEN_HTML###');
						$subject = $this->cObj->getSubpart($template, '###SUBJECT_OFFEN###'); 
		        break;
		    case 2:
		        /* inBearbeitung : send Email */
						$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_IN_BEARBEITUNG_PLAIN###');
						$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_IN_BEARBEITUNG_HTML###'); 
						$subject = $this->cObj->getSubpart($template, '###SUBJECT_IN_BEARBEITUNG###');				
		        break;
		    case 3:
		        /* nachreichung : send Email with comments */
						$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_NACHREICHUNG_PLAIN###');
						$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_NACHREICHUNG_HTML###'); 
						$subject = $this->cObj->getSubpart($template, '###SUBJECT_NACHREICHUNG###'); 					
		        break;
		    case 6:
		        /* entschieden : send Email */
						if ($aData['tx_kbks_ergebnis']==2) {
							/* angenommen */
							$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_ANGENOMMEN_PLAIN###');
							$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_ANGENOMMEN_HTML###');
							$subject = $this->cObj->getSubpart($template, '###SUBJECT_ANGENOMMEN###'); 						
						} elseif ($aData['tx_kbks_ergebnis']==1) {
							/* abgelehnt */
							$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_ABGELEHNT_PLAIN###');
							$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_ABGELEHNT_HTML###');
							$subject = $this->cObj->getSubpart($template, '###SUBJECT_ABGELEHNT###'); 						
						} 
		        break;
		    case 7:
		        /* förderung überwiesen : send Email */
						$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_UEBERWIESEN_PLAIN###');
						$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_UEBERWIESEN_HTML###'); 
						$subject = $this->cObj->getSubpart($template, '###SUBJECT_UEBERWIESEN###'); 					
		        break;
		    case 8:
		        /* abgeschlossen : send Email */
						$subpartPlain = $this->cObj->getSubpart($template, '###MAIL_ABGESCHLOSSEN_PLAIN###');
						$subpartHtml = $this->cObj->getSubpart($template, '###MAIL_ABGESCHLOSSEN_HTML###'); 
						$subject = $this->cObj->getSubpart($template, '###SUBJECT_ABGESCHLOSSEN###'); 					
		        break;
		    default:
		       /* do nothing */;
			}
		}

		if ($subpartPlain && $subpartHtml && $subject) {
		
			foreach($aData as $k => $v) {
				if(substr($k, 0, 8) == 'tx_kbks_') {
					$markerArray['###' . strtoupper(substr($k, 8)) . '###'] = $v;
				}
			} 
			$statusRecord = $this->getStatus($status);
			$markerArray['###STATUS###'] = $statusRecord['tx_kbks_titel_extern'];
			$markerArray['###LINK###'] = t3lib_div::locationHeaderUrl($this->pi_getPageLink($this->conf['pidUserHome']));
			
			$bodyPlain = $this->cObj->substituteMarkerArray($subpartPlain, $markerArray);
	    $bodyHtml = $this->cObj->substituteMarkerArray($subpartHtml, $markerArray);
		
			$bool = $this->sendEmail($aData['tx_kbks_email'], $subject, $bodyPlain, $bodyHtml);
		}
    
		return true;
	}
	
	/**
	 * Returns true if the user has rights to set the status to this value
	 * tests if the user is a Projektleiter, returns false if not and status is freshly set to 6 or 8
	 *
	 * @return	boolean
	 */
	function checkStatus($value) {
		if ($value!=$this->record['tx_kbks_status'] && !$this->isProjektleiter() && ($value==6 || $value==8)) {
			return false;
		} else {
			return true;
		} 
	}	
	
	/**
	 * Returns true if the form should be readonly
	 * tests if the user is not an admin and the form comes from db (has a uid)	 
	 *
	 * @return	boolean
	 */
	function isReadOnly() {
		return ( ! $this->isAdmin() ) && ( $this->uid > 0 );
	}

	/**
	 * Validates a string: format has to be dd.mm.yyyy or d.m.yyyy
	 * @param string $string
	 * @return boolean
	 */
	public function validateDate($value){		

		if($value) {
			if(strlen($value)>10) {
				return false;
			} else {
				$matchCount = preg_match('/(0?[1-9]|[12][0-9]|3[01])\.(0?[1-9]|1[012])\.(19|20)([0-9]{2})/',$value,$matches,PREG_OFFSET_CAPTURE);
				return ($matchCount>0);
			}
		}
		return true;
	}

	/**
	 * Gets triggered on formsubmit
	 * @param array $data 
	 */
	public function onUpdate(&$data){
		$data["pid"] = $GLOBALS["TSFE"]->id;
		$data["cruser_id"] = $GLOBALS["TSFE"]->fe_user->user["uid"];
		$data["tstamp"] = time();
	}

	/**
	 * Gets triggered on formsubmit
	 * @param array $data
	 */
	public function onInsert(&$data){
		$data["crdate"] = time();
		$data["pid"] = $this->generalTS['pidAntraege'];
		$data["cruser_id"] = $GLOBALS["TSFE"]->fe_user->user["uid"];
		$data["tstamp"] = time();
		$data["tx_kbks_fe_user"] = $GLOBALS["TSFE"]->fe_user->user["uid"];
		$data["tx_kbks_status"] = 1;
		if ($this->checkDuplicates($data['tx_kbks_vorname'], $data['tx_kbks_nachname'], $data['tx_kbks_svnr'], $data['tx_kbks_geburtsdatum'])) {
			$data['tx_kbks_dublette'] = 1;
		}
	}

	/**
	 * Returns Configuration Array for this form from the database
	 *
	 * @return	Array of config-values
	 */
	function getConfigArray($tableKey) {
		$resultArray = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_topstip_configuration', 'deleted=0 AND tx_kbks_tablekey=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tableKey, 'tx_kbks_topstip_configuration'));
		return $resultArray[0];
	}

	/**
	 * Returns record of current form (based on  $this->uid and table (from configArray)
	 *
	 * @return	Array of db-row
	 */
	function getRecord() {
		$resultArray = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', $this->configArray['tx_kbks_tablename'], 'deleted=0 AND uid=' . $this->uid);
		return $resultArray[0];
	}
	
	/**
	 * Returns an Array of Universities from the database
	 *
	 * @return	Array of Universities 
	 */
	function getHochschuleArray() {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_hochschule h, tx_kbks_topstip_configuration__hochschule__mm mm', 'deleted=0 AND mm.uid_foreign=h.uid AND mm.uid_local='. $this->configArray['uid']);
	}	

	/**
	 * Returns an Array of foreign Universities from the database
	 *
	 * @return	Array of foreign Universities 
	 */
	function getHochschuleAuslandArray() {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_hochschule', 'deleted=0 AND tx_kbks_inlaendisch!=1');
	}	
		
	/**
	 * Returns an Array of branches of studies from the database
	 *
	 * @return	Array of branches of studies
	 */
	function getStudienrichtungArray() {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_studienrichtung s, tx_kbks_topstip_configuration__studienrichtung__mm mm', 'deleted=0 AND mm.uid_foreign=s.uid AND mm.uid_local='. $this->configArray['uid']);
	}		

	/**
	 * Returns an Array of countries from the database
	 *
	 * @return	Array of Countries
	 */
	function getLandArray() {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_land', 'deleted=0');
	}
	
	/**
	 * Returns an Array of States from the database
	 *
	 * @return	Array of States
	 */
	function getStatusArray() {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_status', 'deleted=0 AND hidden=0');
	}

	/**
	 * Returns a state from the database
	 *
	 * @return	state record
	 */
	function getStatus($uid) {	
		$statusArray = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows ('*', 'tx_kbks_status', 'deleted=0 AND hidden=0 AND uid=' . $uid);
		return $statusArray[0];
	}

	/**
	 * returns the url-path of saved images
	 *
	 * @return	string path
	 */
	function getImagePath($field) {
		global $TCA;
		$tableName = $this->configArray['tx_kbks_tablename'];
		return $TCA[$tableName]['columns'][$field]['config']['uploadfolder'].'/';
	}

	/**
	 * returns the uid of the page to redirect to after form submit
	 *
	 * @return	uid
	 */
	function getRedirectUid() {	
		if ($this->isAdmin()) {
			return $this->conf['pidAdminHome'];
		} else {
			return $this->conf['pidUserHome'];
		}
	}

	/**
	 * returns true if there are duplicates (actually more records of the same person)
	 *
	 * @param  vorname, nachname, svnr, birthdate
	 *	 	 
	 * @return	uid
	 */
	function checkDuplicates($vorname, $nachname, $svnr, $geburtsdatum) {	
		$query = $this->getQuery('tx_kbks_vorname, tx_kbks_nachname', "tx_kbks_nachname LIKE '". $nachname ."' AND tx_kbks_vorname LIKE '". $vorname ."' AND tx_kbks_svnr LIKE '". $svnr ."' AND (tx_kbks_geburtsdatum between ".intval($geburtsdatum)."-43200 and ".intval($geburtsdatum)."+43200)");
		$res = $this->db->sql_query($query);
		while($row = $this->db->sql_fetch_assoc($res)){
			if($row['tableName']=='tx_topstip_ausland') {
				$ausland++;
			} elseif ($row['tableName']=='tx_topstip_diplom') {
				$diplom++;
			} else {
				$rest++;
			};
		}
		if ($rest>1 || ($ausland + $diplom + $rest) > 2) {
			return true;
		}
		else { 
			return false;
		}
	}

  /**
   * sendEmail Method
   * sends the Email
   *	 	       
   * @return       boolean success
   */
  function sendEmail($recipient, $subject, $bodyPlain, $bodyHtml) {

    $emailObj = t3lib_div::makeInstance('t3lib_htmlmail');
    $emailObj->start();
    $emailObj->subject = $subject;
    $emailObj->from_email = $this->conf['from_email'];
    $emailObj->from_name = $this->conf['from_name'];
    $emailObj->replyto_email = $this->conf['replyto_email'];
    $emailObj->replyto_name = $this->conf['replyto_name'];
    $emailObj->returnPath = '';

	  if ($bodyPlain) {
	    $emailObj->addPlain($bodyPlain);
	  }
    if ($bodyHtml) {
      $emailObj->setHTML($emailObj->encodeMsg($bodyHtml));
    }

  	$sent = $emailObj->send($recipient);
  
  	return $sent;
  }	
	
}


if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/test/pi1/class.tx_test_pi1.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/test/pi1/class.tx_test_pi1.php']);
}

?>